import React,{Component} from 'react'
import PublicHeader from '@/components/header/header.jsx'
import TouchableOpacity from '@/components/TouchableOpacity/TouchableOpacity.jsx'
import PublicAlert from '@/components/alert/alert.jsx'
import './balance.less'
import API from '@/api/api'
export default class Balance extends Component{
  
  constructor(props){
    super(props)
    this.state = {
      alertStatus:false,
      balance:{
        balance:0
      },
      alertTip:'',
      applyNum:''
    }
    this.initData()
  }
  initData = async () =>{
    try{
      let result = await API.getBalance()
      console.log(result)
      this.setState({
        balance:result
      })
    }catch(err){
      console.log(err)
    }   
  }

  submitForm = () =>{
    let alertTip
    if(!this.state.applyNum){
      alertTip = '请输入提现金额'
    }else if(parseFloat(this.state.applyNum) > this.state.balance.balance){
      alertTip = '申请提现金额不能大于余额'
    }else{
      alertTip='申请提现成功'
    }
    this.setState({
      alertStatus:true,
      alertTip,
      applyNum:''
    })
    //TODO async commit form 
  }
  handleInput = (event) =>{
    let value = event.target.value;
    if((/^\d*?\.?\d{0,2}?$/gi).test(value)){
      // 数组0开头则把0替换成空字符串
      if((/^0+[1-9]+/).test(value)) {
        value = value.replace(/^0+/,'');
      }
      // 若输入第一位是小数点则在前面补0
      if((/^0{2}\./).test(value)) {
        value = value.replace(/^0+/,'0');
      }
      value = value.replace(/^\./gi,'0.');
      if(parseFloat(value) > 200){
        value = '200.00';
      }
      this.setState({
        applyNum:value
      })
    }
  }
  closeAlert = () =>{
    this.setState({
      alertStatus:false
    })
  }

  render = () =>(
    <main className="home-container">
      <PublicHeader title="提现"></PublicHeader>
      <section className="broke-main-content">
        <p className="broke-header">你可以提现的现金为：￥{this.state.balance.balance}</p>
        <form className="broke-form">
          <p>请输入提现金额(元)</p>
          <p>￥<input type="text" value={this.state.applyNum} placeholder="0.00" onInput={this.handleInput} maxLength='5' /></p>
        </form>
        <TouchableOpacity className="submit-btn" clickCallBack={this.submitForm} text='申请提现'></TouchableOpacity>
      </section>
      <PublicAlert closeAlert={this.closeAlert} alertTip={this.state.alertTip} alertStatus={this.state.alertStatus}></PublicAlert>
    </main>  
  )
    
  
}